<template>
  <div class="chat-container" 
       ref="chatContainer"
       :style="{ left: position.x + 'px', top: position.y + 'px' }"
       @mousedown="startDrag">
    <!-- 添加关闭按钮 -->
    <div class="close-button" @click="closeChat">
      <el-icon class="close-icon"><Close /></el-icon>
    </div>

    <!-- 聊天列表侧边栏 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <h3>消息列表</h3>
      </div>
      
      <div v-if="chatList.length > 0" class="chat-list">
        <div v-for="chat in chatList" 
             :key="chat.id"
             :class="['chat-item', { 'active': currentChat && currentChat.id === chat.id }]"
             @click="selectChat(chat)">
          <div class="avatar">
            <el-avatar :src="chat.avatar || defaultAvatar" />
          </div>
          <div class="chat-info">
            <div class="name-time">
              <span class="name">{{ chat.name }}</span>
              <span class="time">{{ formatTime(chat.timestamp) }}</span>
            </div>
            <div class="last-message">{{ chat.lastMessage }}</div>
          </div>
          <div v-if="chat.unread" class="unread-badge"></div>
        </div>
      </div>
      
      <div v-else class="empty-state">
        <el-empty description="暂无消息" />
      </div>
    </div>

    <!-- 聊天主界面 -->
    <div class="chat-main">
      <template v-if="currentChat">
        <div class="chat-header">
          <span class="chat-title">{{ currentChat.name }}</span>
        </div>

        <div class="message-list" ref="messageList">
          <template v-for="msg in messages" :key="msg.id">
            <div v-if="msg && shouldShowDate(msg)" class="time-divider">
              {{ formatDate(msg.timestamp) }}
            </div>
            
            <!-- 自己发送的消息 -->
            <div v-if="msg.senderId === consultantId" class="message self">
              <div class="avatar">
                <el-avatar :src="userInfo?.consultantAvatar || defaultAvatar" />
              </div>
              <div class="message-content">
                <div class="message-bubble vue">
                  {{ msg.content }}
                </div>
              </div>
            </div>
            
            <!-- 对方发送的消息 -->
            <div v-else class="message">
              <div class="avatar">
                <el-avatar :src="currentChat?.avatar || defaultAvatar" />
              </div>
              <div class="message-content">
                <div class="message-bubble wx">
                  {{ msg.content }}
                </div>
              </div>
            </div>
          </template>
        </div>

        <div class="input-area">
          <input v-model="inputContent" 
                 @keyup.enter="sendMessage" 
                 placeholder="请输入消息..."/>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </template>
      
      <div v-else class="no-chat-selected">
        <el-empty description="请选择一个聊天" />
      </div>
    </div>
  </div>
</template>

<script setup lang="js">
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElEmpty, ElAvatar, ElButton, ElMessage } from 'element-plus'
import { Close } from '@element-plus/icons-vue'  // 引入关闭图标
import axios from 'axios';


const route = useRoute()
const router = useRouter()
const messages = ref([])
const inputContent = ref('')
const websocket = ref(null)
const consultantId = ref(null)
const currentChat = ref(null)
const chatList = ref([])
const userInfo = ref(null)

// 修改聊天列表的数据结构，使用 Map 来存储
const chatMap = ref(new Map()); // key: senderId, value: 聊天信息

// 获取消息列表
const fetchChatList = async () => {
  if (!consultantId.value) {
    console.error('未获取到咨询师ID')
    ElMessage.error('请先登录')
    return
  }

  try {
    console.log('正在获取消息列表，consultantId:', consultantId.value)
    const response = await fetch(`http://120.26.112.194:80/apii/chat/list?consultantId=${consultantId.value}`)
    const data = await response.json()
    if (data.code === 200) {
      // 确保每个聊天项都有必要的字段
      chatList.value = data.data.map(chat => ({
        id: chat.senderId,  // 使用发送者ID作为聊天项的ID
        name: chat.name || `用户${chat.senderId}`,
        avatar: chat.avatar,
        lastMessage: chat.lastMessage,
        timestamp: chat.timestamp,
        senderId: chat.senderId
      }))
    }
  } catch (error) {
    console.error('获取消息列表失败:', error)
    ElMessage.error('获取消息列表失败')
  }
}

// 打开聊天
const openChat = (chat) => {
  currentChat.value = chat
  // 清除未读标记
  const index = chatList.value.findIndex(item => item.id === chat.id)
  if (index !== -1) {
    chatList.value[index].unread = false
  }
  // 加载历史消息
  loadChatHistory(chat.id)
}

// 返回列表
const backToList = () => {
  currentChat.value = null
  if (websocket.value) {
    websocket.value.close()
  }
}

// WebSocket连接
const connectWebSocket = () => {
  if (websocket.value) {
    console.log('WebSocket 已连接，无需重新连接')
    return
  }
  
  const wsUrl = `ws://120.26.112.194:80/apii/websocket/chat?userId=${consultantId.value}`
  console.log('正在连接WebSocket:', wsUrl)
  
  websocket.value = new WebSocket(wsUrl)
  
  websocket.value.onopen = () => {
    console.log('WebSocket连接已建立')
  }
  
  websocket.value.onmessage = async (event) => {
    try {
      console.log('收到WebSocket消息:', event.data);
      const message = JSON.parse(event.data);
      
      if (message.code === 200 && message.data) {
        const messageData = message.data;
        
        // 添加新消息到消息列表
        messages.value.push({
          id: Date.now(),
          ...messageData
        });
        
        // 重新获取消息列表
        await fetchChatList();
        
        // 滚动到底部
        scrollToBottom();
      }
    } catch (error) {
      console.error('处理WebSocket消息失败:', error);
    }
  };
}

// 更新聊天列表的方法
const updateChatList = (messageData) => {
  const senderId = messageData.senderId;
  const receiverId = messageData.receiverId;
  
  // 确定要更新的聊天ID和信息
  let chatId, chatName, chatAvatar;
  if (senderId === consultantId.value) {
    // 如果是自己发送的消息，显示接收者信息
    chatId = receiverId;
    chatName = messageData.receiverName;
    chatAvatar = messageData.receiverAvatar;
  } else {
    // 如果是收到的消息，显示发送者信息
    chatId = senderId;
    chatName = messageData.senderName;
    chatAvatar = messageData.senderAvatar;
  }
  
  // 更新或创建聊天项
  if (chatMap.value.has(chatId)) {
    const existingChat = chatMap.value.get(chatId);
    existingChat.lastMessage = messageData.content;
    existingChat.timestamp = messageData.timestamp;
    existingChat.unread = senderId !== consultantId.value && 
                         currentChat.value?.id !== chatId;
  } else {
    chatMap.value.set(chatId, {
      id: chatId,
      name: chatName || `用户${chatId}`,
      avatar: chatAvatar || defaultAvatar,
      lastMessage: messageData.content,
      timestamp: messageData.timestamp,
      unread: senderId !== consultantId.value && currentChat.value?.id !== chatId
    });
  }
  
  // 更新聊天列表并保持排序
  chatList.value = Array.from(chatMap.value.values())
    .sort((a, b) => b.timestamp - a.timestamp);
};

// 初始化时加载聊天列表
const initChatList = async () => {
  try {
    const response = await fetch(`http://120.26.112.194:80/apii/chat/list?consultantId=${consultantId.value}`);
    const data = await response.json();
    if (data.code === 200) {
      // 将所有聊天添加到 Map 中
      data.data.forEach(chat => {
        chatMap.value.set(chat.senderId, {
          id: chat.senderId,
          name: chat.name || `用户${chat.senderId}`,
          avatar: chat.avatar || defaultAvatar,
          lastMessage: chat.lastMessage,
          timestamp: chat.timestamp,
          unread: chat.unread || false
        });
      });
      
      // 更新聊天列表
      chatList.value = Array.from(chatMap.value.values())
        .sort((a, b) => b.timestamp - a.timestamp);
    }
  } catch (error) {
    console.error('获取聊天列表失败:', error);
    ElMessage.error('获取聊天列表失败');
  }
};

// 发送消息
const sendMessage = async () => {
  if (!inputContent.value.trim() || !websocket.value || !currentChat.value) return;
  
  const message = {
    senderId: consultantId.value,
    senderName: userInfo.value.consultantName,
    senderAvatar: userInfo.value.consultantAvatar,
    receiverId: currentChat.value.id,
    receiverName: currentChat.value.name,
    receiverAvatar: currentChat.value.avatar,
    content: inputContent.value.trim(),
    timestamp: Date.now(),
    type: 'vue'
  };
  
  try {
    websocket.value.send(JSON.stringify(message));
    
    // 立即添加到本地消息列表
    messages.value.push({
      id: Date.now(),
      ...message
    });
    
    // 清空输入框
    inputContent.value = '';
    
    // 滚动到底部
    scrollToBottom();
    
    // 重新获取消息列表
    await fetchChatList();
    
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送失败，请重试');
  }
};

// 处理接收到的消息
const handleMessage = (event) => {
  try {
    const message = JSON.parse(event.data);
    console.log('收到消息:', message);
    
    if (message.code === 200 && message.data) {
      const messageData = message.data;
      const senderId = messageData.senderId;
      
      // 更新消息列表
      messages.value.push({
        id: Date.now(),
        senderId: senderId,
        senderName: messageData.senderName,
        content: messageData.content,
        timestamp: messageData.timestamp,
        type: messageData.type || 'vue'
      });
      
      // 如果当前没有选中的聊天，或者选中的不是当前发送者，则更新聊天列表
      if (!currentChat.value || currentChat.value.id !== senderId) {
        updateChatList({
          id: senderId,
          senderName: messageData.senderName,
          senderAvatar: messageData.senderAvatar,
          content: messageData.content,
          timestamp: messageData.timestamp
        });
      }
      
      scrollToBottom();
    }
  } catch (error) {
    console.error('处理消息失败:', error);
  }
};

// 滚动到底部
const messageList = ref(null)
const scrollToBottom = () => {
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  
  const now = new Date();
  const date = new Date(timestamp);
  const diffMinutes = Math.floor((now - date) / (1000 * 60));
  const diffHours = Math.floor(diffMinutes / 60);
  const diffDays = Math.floor(diffHours / 24);
  
  // 如果是今天
  if (diffDays === 0) {
    // 如果小于1小时
    if (diffHours === 0) {
      if (diffMinutes <= 1) {
        return '刚刚';
      }
      return `${diffMinutes}分钟前`;
    }
    // 今天的其他时间显示具体时间
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit',
      hour12: false 
    });
  }
  
  // 如果是昨天
  if (diffDays === 1) {
    return '昨天';
  }
  
  // 如果是前天
  if (diffDays === 2) {
    return '前天';
  }
  
  // 其他日期显示月日
  return `${date.getMonth() + 1}月${date.getDate()}日`;
};

// 添加加载历史消息的方法
const loadChatHistory = async (chatId) => {
  try {
    const response = await fetch(`http://120.26.112.194:80/apii/chat/history?consultantId=${consultantId.value}&userId=${chatId}`)
    const data = await response.json()
    if (data.code === 200) {
      messages.value = data.data.map(msg => ({
        id: msg.id,
        senderId: msg.senderId,
        senderName: msg.senderName,
        senderAvatar: msg.senderAvatar,
        content: msg.content,
        timestamp: msg.timestamp
      }))
      scrollToBottom()
    }
  } catch (error) {
    console.error('获取历史消息失败:', error)
    ElMessage.error('获取历史消息失败')
  }
}

// 修改消息分组方法
const groupMessages = (messages) => {
  const grouped = [];
  let currentGroup = null;

  messages.forEach(msg => {
    if (!currentGroup || currentGroup.senderId !== msg.senderId) {
      currentGroup = {
        id: msg.id || Date.now(), // 确保有 id
        senderId: msg.senderId,
        senderName: msg.senderId === consultantId.value ? 
          userInfo.value?.consultantName : 
          (msg.senderName || '用户'),
        messages: [{
          content: msg.content,
          timestamp: msg.timestamp || Date.now() // 确保有时间戳
        }]
      };
      grouped.push(currentGroup);
    } else {
      currentGroup.messages.push({
        content: msg.content,
        timestamp: msg.timestamp || Date.now()
      });
    }
  });

  return grouped;
};

// 添加计算属性来获取分组后的消息
const groupedMessages = computed(() => {
  return groupMessages(messages.value)
})

// 添加一个计算属性来对聊天列表进行排序
const sortedChatList = computed(() => {
  console.log('重新计算排序的聊天列表', chatList.value) // 添加日志
  return [...chatList.value].sort((a, b) => b.timestamp - a.timestamp)
})

// 修改判断是否显示日期的方法
const shouldShowDate = (message) => {
  if (!message || !message.timestamp) return false;
  
  const index = messages.value.findIndex(msg => msg.id === message.id);
  if (index === 0) return true;
  
  const currentDate = new Date(message.timestamp).toDateString();
  const prevDate = new Date(messages.value[index - 1].timestamp).toDateString();
  
  return currentDate !== prevDate;
};

// 修改时间格式化函数
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);

  if (date.toDateString() === today.toDateString()) {
    return '今天';
  } else if (date.toDateString() === yesterday.toDateString()) {
    return '昨天';
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  }
};

// 选择聊天的方法
const selectChat = async (chat) => {
  currentChat.value = chat;
  // 加载历史消息
  await loadChatHistory(chat.id);
  // 标记为已读
  chat.unread = false;
};

// 添加关闭方法
const closeChat = () => {
  router.go(-1)  // 返回上一页
}

// 添加拖拽相关的状态
const chatContainer = ref(null)
const position = ref({ x: 100, y: 100 }) // 初始位置
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })

// 开始拖拽
const startDrag = (e) => {
  // 如果点击的是输入框或按钮，不启动拖拽
  if (e.target.tagName === 'INPUT' || 
      e.target.tagName === 'BUTTON' || 
      e.target.classList.contains('close-button')) {
    return
  }
  
  isDragging.value = true
  dragOffset.value = {
    x: e.clientX - position.value.x,
    y: e.clientY - position.value.y
  }
  
  // 添加移动和停止拖拽的事件监听
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('mouseup', stopDrag)
}

// 拖拽过程
const handleDrag = (e) => {
  if (!isDragging.value) return
  
  position.value = {
    x: e.clientX - dragOffset.value.x,
    y: e.clientY - dragOffset.value.y
  }
}

// 停止拖拽
const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}

onMounted(() => {
  const storedUserInfo = JSON.parse(sessionStorage.getItem('user'))
  if (storedUserInfo && storedUserInfo.consultantId) {
    userInfo.value = storedUserInfo
    consultantId.value = storedUserInfo.consultantId.toString()
    
    // 获取消息列表
    fetchChatList()
    // 建立 WebSocket 连接
    connectWebSocket()
  } else {
    ElMessage.error('请先登录')
    router.push('/login')
  }
})

onUnmounted(() => {
  if (websocket.value) {
    websocket.value.close()
    websocket.value = null
  }
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
})
</script>

<style scoped>
.chat-container {
  position: fixed; /* 改为 fixed 定位 */
  width: 800px;  /* 设置固定宽度 */
  height: 600px; /* 设置固定高度 */
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  overflow: hidden;
  user-select: none; /* 防止拖拽时选中文本 */
  z-index: 1000; /* 确保在其他元素上方 */
}

.chat-sidebar {
  width: 250px; /* 稍微减小侧边栏宽度 */
  border-right: 1px solid #eee;
  background: white;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-main {
  width: calc(100% - 250px); /* 主聊天区域宽度等于容器宽度减去侧边栏宽度 */
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
  height: calc(100% - 60px); /* 减去头部的高度 */
}

.chat-item {
  position: relative;
  display: flex;
  padding: 15px 20px;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
  align-items: center; /* 垂直居中对齐 */
  gap: 12px; /* 添加头像和内容之间的间距 */
}

.chat-item:hover {
  background: #f9f9f9;
}

.chat-item.active {
  background: #e6f7ff;
}

.message {
  display: flex;
  align-items: flex-start;
  margin: 20px 0;
  padding: 0 20px;
  gap: 12px;
}

/* 自己发送的消息样式 */
.message.self {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  margin-right: 4px; /* 额外添加一点间距 */
}

.avatar .el-avatar {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.message-content {
  max-width: 70%;
}

.message-bubble {
  padding: 10px 16px;
  border-radius: 4px;
  word-break: break-word;
}

/* 小程序消息样式 */
.message-bubble.wx {
  background-color: #fff;
  color: #333;
}

/* Vue端消息样式 */
.message-bubble.vue {
  background-color: #007AFF;
  color: #fff;
}

.time-divider {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin: 20px 0;
}

.input-area {
  padding: 20px;
  background: white;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 10px;
  height: 80px; /* 固定输入区域高度 */
  position: relative;
  bottom: 0;
  left: 0;
  right: 0;
}

.input-area input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.no-chat-selected {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
}

.chat-header {
  padding: 20px;
  background: white;
  border-bottom: 1px solid #eee;
  height: 60px; /* 固定头部高度 */
  display: flex;
  align-items: center;
  cursor: move; /* 显示移动光标 */
}

.chat-title {
  font-size: 16px;
  font-weight: 500;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f5f5;
  height: calc(100% - 140px); /* 减去头部和输入框的高度 */
}

.message-group {
  display: flex;
  margin: 20px 0;
  align-items: flex-start;
  padding: 0 20px;
  gap: 12px; /* 添加间距 */
}

.message-group.self {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
}

.avatar .el-avatar {
  width: 100%;
  height: 100%;
  border-radius: 4px; /* 方形头像 */
}

.message-content-group {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-group.self .message-content-group {
  align-items: flex-end; /* 让自己发送的消息靠右对齐 */
}

.message-bubble {
  position: relative;
  margin: 2px 0;
  padding: 10px 16px;
  border-radius: 4px;
  word-break: break-word;
  max-width: 100%;
}

.message-group.self .message-bubble {
  background: #95EC69;
  color: #000;
  border-radius: 4px;
}

.message-group:not(.self) .message-bubble {
  background: white;
  border-radius: 4px;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: center;
}

/* 优化输入框样式 */
.input-area {
  background: #F5F5F5;
  padding: 10px 20px;
  border-top: 1px solid #E7E7E7;
}

.input-area input {
  background: white;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  height: 40px;
}

.input-area button {
  background: #07C160;
  border: none;
  border-radius: 4px;
  height: 40px;
}

.input-area button:hover {
  background: #06AE56;
}

/* 优化滚动条样式 */
.message-list::-webkit-scrollbar,
.chat-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-thumb,
.chat-list::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-track,
.chat-list::-webkit-scrollbar-track {
  background-color: transparent;
}

/* 消息气泡样式优化 */
.message-bubble {
  margin: 2px 0;
  max-width: 70%;
  word-break: break-word;
  padding: 12px 16px;
  border-radius: 10px;
}

.message-group.self .message-bubble {
  background: #007AFF;
  color: white;
  margin-left: auto;
}

.message-group:not(.self) .message-bubble {
  background: white;
  margin-right: auto;
}

/* 输入框样式优化 */
.input-area input {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.input-area input:focus {
  border-color: #007AFF;
}

.input-area button {
  padding: 8px 24px;
  border-radius: 20px;
}

/* 添加时间分组样式 */
.time-divider {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin: 20px 0;
}

/* 可以为不同类型的消息添加不同的样式 */
.message.miniprogram .content {
  /* 小程序消息的特殊样式 */
  background-color: #f0f0f0;
}

.message.self .content {
  /* Vue端发送的消息样式 */
  background-color: #95EC69;
}

.unread-badge {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ff4d4f;
  position: absolute;
  right: 10px;
  top: 10px;
}

.chat-item.active {
  background-color: #e6f7ff;
}

.chat-info {
  flex: 1;
  min-width: 0; /* 防止文本溢出 */
  margin-right: 8px; /* 给时间留出空间 */
  padding-left: 4px; /* 给内容添加左边距 */
}

.name-time {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
  flex-shrink: 0; /* 防止时间被压缩 */
  margin-left: auto; /* 将时间推到最右边 */
}

.last-message {
  font-size: 13px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 添加关闭按钮样式 */
.close-button {
  position: absolute;
  top: 16px;
  right: 16px;
  cursor: pointer;
  z-index: 100;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s;
}

.close-button:hover {
  background-color: rgba(0, 0, 0, 0.2);
}

.close-icon {
  font-size: 20px;
  color: #666;
}
</style> 